package com.zg.shop.order;


import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zg.shop.cart.Cart;
import com.zg.shop.cart.CartItem;
import com.zg.shop.common.Constant;
import com.zg.shop.product.PageBean;
import com.zg.shop.user.User;
import com.zg.shop.utils.LoggerUtils;
import com.zg.shop.utils.PaymentUtil;


public class OrderAction extends ActionSupport{

	private Order order = new Order();
	private OrderService orderService;
	private String pd_FrpId;
	private Integer oid;
	private Integer page;
	private Integer state;
	
	public void setPage(Integer page) {
		this.page = page;
	}
	public void setState(Integer state) {
		this.state = state;
	}
	public void setOid(Integer oid) {
		this.oid = oid;
	}

	//付款成功后需要的参数
	private String r3_Amt;//金额
	private String r6_Order;//订单编号
	
	public void setR3_Amt(String r3_Amt) {
		this.r3_Amt = r3_Amt;
	}
	public void setR6_Order(String r6_Order) {
		this.r6_Order = r6_Order;
	}
	
	public void setPd_FrpId(String pd_FrpId) {
		this.pd_FrpId = pd_FrpId;
	}
	public Order getOrder() {
		return order;
	}
	
	public void setOrder(Order order) {
		this.order = order;
	}
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}
	
	
	
	public String saveOrder(){
		order = new Order();
		//封装数据start
		//setOrdertime会导致插入失败，据说换最新的mysql驱动jar就可以了，然后我换了新的jar包，果然好了
		order.setOrdertime(new Date());
		order.setState(Constant.ORDERUNPAID);
		
		HttpServletRequest request = ServletActionContext.getRequest();
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart == null){
			this.addActionMessage("您还没有购物，请先去购物");
			return "saveOrderMessage";
		}
		order.setTotal(cart.getTotal());
		
		User existUser = (User) request.getSession().getAttribute("existUser");
		if(existUser == null){
			LoggerUtils.logger.info("======================================");
			this.addActionMessage("您还没有登录，请登录");
			return "saveOrderMessage";
		}
		order.setUser(existUser);
		
		
		
		//订单项的数据，从购物项获得。
		for(CartItem cartItem : cart.getCartItems()){
			OrderItem orderItem = new OrderItem();
			orderItem.setCount(cartItem.getCount());
			orderItem.setSubtotal(cartItem.getSubtotal());
			orderItem.setProduct(cartItem.getProduct());
			orderItem.setOrder(order);
			
			order.getOrderItems().add(orderItem);
		}
		
		cart.clearCart();
		
		Integer oid = orderService.saveOrder(order);
		
		//封装数据end
		
		//为了在页面拿到完整的数据
		//order = orderService.findByOid(oid);
		order.setOid(oid);
		
		return "savaOrderSuccess";
	}
	
	public String payOrder() throws IOException{
	
		//修改订单
		Order currOrder = orderService.findByOid(order.getOid());
		currOrder.setAddr(order.getAddr());
		currOrder.setName(order.getName());
		currOrder.setPhone(order.getPhone());
		
		orderService.update(currOrder);
		//付款
		//定义付款的参数
		String p0_Cmd = "Buy";//固定的
		String p1_MerId = "10001126856";//易宝公开的公益帐号
		String p2_Order = order.getOid().toString();//订单编号
		String p3_Amt = "0.01";//金额
		String p4_Cur = "CNY";//币种
		String p5_Pid = "";//商品名称
		String p6_Pcat = "";//商品种类
		String p7_Pdesc = "";//商品描述
		String p8_Url = "http://192.168.10.35:8080/order_callBack.action";//成功以后回到那里?
		String p9_SAF = "";//送货地址
		String pa_MP = "";//商户扩展信息
		//String pd_FrpId = pd_FrpId;//支付通道编号//在上边已经获得了。
		String pr_NeedResponse = "1";//应答机制
		String keyValue = "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl";//商户密钥
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue);
		
		StringBuffer sb = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?");
		sb.append("p0_Cmd=").append(p0_Cmd).append("&");
		sb.append("p1_MerId=").append(p1_MerId).append("&");
		sb.append("p2_Order=").append(p2_Order).append("&");
		sb.append("p3_Amt=").append(p3_Amt).append("&");
		sb.append("p4_Cur=").append(p4_Cur).append("&");
		sb.append("p5_Pid=").append(p5_Pid).append("&");
		sb.append("p6_Pcat=").append(p6_Pcat).append("&");
		sb.append("p7_Pdesc=").append(p7_Pdesc).append("&");
		sb.append("p8_Url=").append(p8_Url).append("&");
		sb.append("p9_SAF=").append(p9_SAF).append("&");
		sb.append("pa_MP=").append(pa_MP).append("&");
		sb.append("pd_FrpId=").append(pd_FrpId).append("&");
		sb.append("pr_NeedResponse=").append(pr_NeedResponse).append("&");
		sb.append("hmac=").append(hmac);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.sendRedirect(sb.toString());
		
		return NONE;
	}

	public String callBack(){
		Order currOrder = orderService.findByOid(Integer.parseInt(r6_Order));
		currOrder.setState(Constant.ORDERPAID);
		orderService.update(currOrder);
		
		this.addActionMessage("订单付款成功，订单号："+r6_Order+"付款金额"+r3_Amt);
		
		return "callBackMsg";
	}
	
	public String findByUid(){
		User existUser = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
		List<Order> orders = orderService.findByUid(existUser.getUid());
		ActionContext.getContext().getValueStack().set("orders", orders);
		return "findByUidSuccess";
	}
	
	public String findByOid(){
		order = orderService.findByOid(oid);
		return "findByOidSuccess";
	}
	public String adminFindByState(){
		PageBean<Order> pageBean = new PageBean<Order>();
		if(state == null){
			pageBean = orderService.findByPage(page);
		}else{
			pageBean = orderService.findByPage(page, state);
		}
		ActionContext.getContext().getValueStack().set("pageBean", pageBean);
		
		return "findOrderSuccess";
	}
	
}

